<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,qt,modbus,">










<meta name="description" content="介绍ScopeModbus 是基于 Python2.7 和 PyQT4 开发的 modbus 通信采集软件，已在 windows、deepin linux 和树莓派上测试！ 目前已开源  Github Gitee  PyQT UI 开发 QT 设计师 使用 QT 设计师设计 layout，再使用 pyuic 进行转换  python 转换代码”~QT_UI_Conv.py” 12345678910">
<meta name="keywords" content="python,qt,modbus">
<meta property="og:type" content="article">
<meta property="og:title" content="Python+QT开发的Modbus采集软件">
<meta property="og:url" content="http://www.soshare.cn/2019/10/15/191015-python-scopemodbus/index.html">
<meta property="og:site_name" content="soshare">
<meta property="og:description" content="介绍ScopeModbus 是基于 Python2.7 和 PyQT4 开发的 modbus 通信采集软件，已在 windows、deepin linux 和树莓派上测试！ 目前已开源  Github Gitee  PyQT UI 开发 QT 设计师 使用 QT 设计师设计 layout，再使用 pyuic 进行转换  python 转换代码”~QT_UI_Conv.py” 12345678910">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-10-15T11:57:46.556Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python+QT开发的Modbus采集软件">
<meta name="twitter:description" content="介绍ScopeModbus 是基于 Python2.7 和 PyQT4 开发的 modbus 通信采集软件，已在 windows、deepin linux 和树莓派上测试！ 目前已开源  Github Gitee  PyQT UI 开发 QT 设计师 使用 QT 设计师设计 layout，再使用 pyuic 进行转换  python 转换代码”~QT_UI_Conv.py” 12345678910">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.soshare.cn/2019/10/15/191015-python-scopemodbus/">



<script data-ad-client="ca-pub-3578624407535320" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>


  <title>Python+QT开发的Modbus采集软件 | soshare</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">soshare</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">分享</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-file">
          <a href="http://taosha126.ys168.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-file"></i> <br>
            
            File
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            Commonweal 404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.soshare.cn/2019/10/15/191015-python-scopemodbus/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="tosobright">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="soshare">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Python+QT开发的Modbus采集软件</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-10-15T09:42:01+08:00">
                2019-10-15
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Program/" itemprop="url" rel="index">
                    <span itemprop="name">Program</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/10/15/191015-python-scopemodbus/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/10/15/191015-python-scopemodbus/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2019/10/15/191015-python-scopemodbus/" class="leancloud_visitors" data-flag-title="Python+QT开发的Modbus采集软件">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">Visitors&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h1><p>ScopeModbus 是基于 Python2.7 和 PyQT4 开发的 modbus 通信采集软件，已在 windows、deepin linux 和树莓派上测试！</p>
<p>目前已开源</p>
<ul>
<li><a href="https://github.com/tosobright/ScopeModbus" target="_blank" rel="noopener">Github</a></li>
<li><a href="https://gitee.com/tosobright/ScopeModbus" target="_blank" rel="noopener">Gitee</a></li>
</ul>
<h1 id="PyQT-UI-开发"><a href="#PyQT-UI-开发" class="headerlink" title="PyQT UI 开发"></a>PyQT UI 开发</h1><ul>
<li><p>QT 设计师</p>
<p>使用 QT 设计师设计 layout，再使用 pyuic 进行转换</p>
<ul>
<li><p>python 转换代码”~QT_UI_Conv.py”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">for</span> root, dirs, files <span class="keyword">in</span> os.walk(<span class="string">'.'</span>):</span><br><span class="line">    <span class="keyword">for</span> file <span class="keyword">in</span> files:</span><br><span class="line">        <span class="keyword">if</span> file.endswith(<span class="string">'.ui'</span>):</span><br><span class="line">            os.system(<span class="string">"D:\Python\Python27\python.exe"</span> <span class="string">' "D:\Python\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" -o ui_%s.py %s'</span> %</span><br><span class="line">                      (file.rsplit(<span class="string">'.'</span>, <span class="number">1</span>)[<span class="number">0</span>], file))</span><br><span class="line">            <span class="comment"># print "D:\Python\Python27\python.exe" ' "D:\Python\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" -o ui_%s.py %s' % (</span></span><br><span class="line">            <span class="comment">#    file.rsplit('.', 1)[0], file)</span></span><br><span class="line">        <span class="keyword">elif</span> file.endswith(<span class="string">'.qrc'</span>):</span><br><span class="line">            os.system(<span class="string">'"D:\Python\Python27\Lib\site-packages\PyQt4\pyrcc4.exe" -o %s_rc.py %s'</span> %</span><br><span class="line">                      (file.rsplit(<span class="string">'.'</span>, <span class="number">1</span>)[<span class="number">0</span>], file))</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用批处理命令处理 ui 文件夹下的所有 layout 文件,并将生成的文件复制到源代码中的 layout，生成的文件统一命名为 <code>ui_layout_(*).py</code></p>
<figure class="highlight bat"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> off</span><br><span class="line"><span class="built_in">echo</span> "_______python build_______"</span><br><span class="line"><span class="built_in">cd</span> ui</span><br><span class="line"><span class="built_in">echo</span> "UI build..."</span><br><span class="line">"D:\Python\Python27\python.exe" ~QT_UI_Conv.py</span><br><span class="line"><span class="built_in">echo</span> "<span class="built_in">Copy</span> image resouce..."</span><br><span class="line"><span class="built_in">copy</span> pyimg_rc.py ..\src\app\layout\pyimg_rc.py</span><br><span class="line"><span class="built_in">echo</span> "<span class="built_in">Copy</span> ui resouce..."</span><br><span class="line"><span class="built_in">copy</span> ui*.py ..\src\app\layout</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>UI 调用</p>
<p>在主程序体中，调用生成的 class</p>
<p>导入即可<code>from layout.ui_layout_main import Ui_MainWindow</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyWindow</span><span class="params">(QtGui.QMainWindow)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super(MyWindow, self).__init__()</span><br><span class="line">        <span class="comment"># 这里需要注意self.ui已经将Ui_MainWindow类实例</span></span><br><span class="line">        <span class="comment"># 化，因此继承了该类的所有属性，后面更改设置属性都用self.ui“冠名”</span></span><br><span class="line">        <span class="comment"># 主UI</span></span><br><span class="line">        self.ui = Ui_MainWindow()</span><br><span class="line">        self.ui.setupUi(self)</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h1 id="多线程"><a href="#多线程" class="headerlink" title="多线程"></a>多线程</h1><p>采集程序既要采集数据，也要显示数据，需使用到多线程</p>
<ul>
<li><p>采集线程</p>
<p>采集线程与主线程通信，进行数据交互</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 采集线程</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AcqThread</span><span class="params">(QtCore.QThread)</span>:</span></span><br><span class="line">    signal_acqdata = QtCore.pyqtSignal(str, list)  <span class="comment"># 信号</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, parent=None)</span>:</span></span><br><span class="line">        super(AcqThread, self).__init__(parent)</span><br><span class="line">        self.bol_working = <span class="literal">True</span></span><br><span class="line">        self.bol_emit = <span class="literal">False</span></span><br><span class="line">        self.int_cyc = <span class="number">1</span>  <span class="comment"># 单位为s</span></span><br><span class="line">        self.num = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">while</span> self.bol_working:</span><br><span class="line">            <span class="comment"># print "Working", self.thread()</span></span><br><span class="line">            <span class="keyword">if</span> self.bol_emit:</span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    self.cmdtxt.setUpdatesEnabled(<span class="literal">False</span>)</span><br><span class="line">                    v = []</span><br><span class="line">                    <span class="keyword">for</span> item <span class="keyword">in</span> self.productpar:</span><br><span class="line">                        func = item[<span class="string">'func'</span>]</span><br><span class="line">                        startaddr = item[<span class="string">'startaddr'</span>]</span><br><span class="line">                        length = item[<span class="string">'length'</span>]</span><br><span class="line">                        d = self.mb.read(func, startaddr, length)</span><br><span class="line">                        <span class="comment">#print func,startaddr,length,d</span></span><br><span class="line">                        <span class="keyword">if</span> item[<span class="string">'type'</span>] == <span class="string">'int'</span>:</span><br><span class="line">                            dv = mbf.ReadInt(d)</span><br><span class="line">                        <span class="keyword">elif</span> item[<span class="string">'type'</span>] == <span class="string">'float'</span>:</span><br><span class="line">                            dv = mbf.ReadFloat(d)</span><br><span class="line">                        <span class="keyword">elif</span> item[<span class="string">'type'</span>] == <span class="string">'list'</span>:</span><br><span class="line">                            dv = mbf.ReadInt(d)</span><br><span class="line">                        <span class="keyword">elif</span> item[<span class="string">'type'</span>] == <span class="string">'bool'</span>:</span><br><span class="line">                            <span class="keyword">if</span> mbf.ReadInt(d) == <span class="number">1</span>:</span><br><span class="line">                                dv = <span class="literal">True</span></span><br><span class="line">                            <span class="keyword">else</span>:</span><br><span class="line">                                dv = <span class="literal">False</span></span><br><span class="line">                        v.append(dv)</span><br><span class="line">                    <span class="comment">#print v</span></span><br><span class="line">                    self.cmdtxt.setUpdatesEnabled(<span class="literal">True</span>)</span><br><span class="line">                    self.num += <span class="number">1</span></span><br><span class="line">                    self.signal_acqdata.emit(</span><br><span class="line">                        <span class="string">"Running:"</span>+str(self.num), v)  <span class="comment"># 发送信号</span></span><br><span class="line">                <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">                    self.cmdtxt.setUpdatesEnabled(<span class="literal">True</span>)</span><br><span class="line">                    <span class="keyword">pass</span></span><br><span class="line">            self.sleep(self.int_cyc)</span><br></pre></td></tr></table></figure>
</li>
<li><p>时间线程</p>
<p>系统时间显示放入单独的线程内</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 时间线程</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TimeThread</span><span class="params">(QtCore.QThread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, parent=None)</span>:</span></span><br><span class="line">        super(TimeThread, self).__init__(parent)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            t = time.strftime(<span class="string">"%Y-%m-%d %H:%M:%S"</span>, time.localtime())</span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line">            self.txt_time.setText(t)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getTimeObj</span><span class="params">(self, obj)</span>:</span></span><br><span class="line">        self.txt_time = obj</span><br></pre></td></tr></table></figure>
</li>
<li><p>主线程</p>
<p>加载线程</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Load thread</span></span><br><span class="line"><span class="comment"># 创建新线程</span></span><br><span class="line">self.threadAcq = AcqThread()</span><br><span class="line"><span class="comment"># thread2 = myThread(2, "Thread-2", 2)</span></span><br><span class="line"><span class="comment"># 连接信号</span></span><br><span class="line">self.threadAcq.signal_acqdata.connect(self.Graph_Update)</span><br><span class="line"><span class="comment"># 开启线程</span></span><br><span class="line">self.threadAcq.start()</span><br><span class="line">self.threadAcq.CommandTxt(self.ui.txt_CMD)</span><br><span class="line"></span><br><span class="line">self.threadTime = TimeThread()</span><br><span class="line">self.threadTime.getTimeObj(self.Txt_time)</span><br><span class="line">self.threadTime.start()</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h1 id="Modbus"><a href="#Modbus" class="headerlink" title="Modbus"></a>Modbus</h1><ul>
<li><p>Modbus RTU</p>
<p>这里采用的是 modbus rtu，是修改自<code>modbus_tk</code>这个标准库，只取了里面的 RTU 部分</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># @author: Toso</span></span><br><span class="line"><span class="comment"># @created: 2019-05-08T13:40:09.624Z+08:00</span></span><br><span class="line"><span class="comment"># @comment: ______________</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> serial</span><br><span class="line"><span class="keyword">import</span> serial.tools.list_ports</span><br><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"><span class="keyword">import</span> MBdefines <span class="keyword">as</span> defines</span><br><span class="line"><span class="keyword">import</span> struct</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> MBFormat</span><br><span class="line"><span class="keyword">from</span> PyQt4 <span class="keyword">import</span> QtCore</span><br><span class="line"></span><br><span class="line">PY2 = sys.version_info[<span class="number">0</span>] == <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MB</span><span class="params">(QtCore.QObject)</span>:</span></span><br><span class="line">    MBrecord = QtCore.pyqtSignal(str)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">ComAutoFind</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.comboBox_Port = []</span><br><span class="line">        <span class="comment"># 先获取所以有USB串口挂载的设备</span></span><br><span class="line">        self.scomList = list(serial.tools.list_ports.comports())</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(len(self.scomList) &lt;= <span class="number">0</span>):</span><br><span class="line">            <span class="keyword">return</span> self.tr(<span class="string">u"No Port Find"</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">for</span> item <span class="keyword">in</span> self.scomList:</span><br><span class="line">                self.comboBox_Port.append(item.device)</span><br><span class="line">        <span class="keyword">return</span> self.comboBox_Port</span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">Open</span><span class="params">(self, DevAddr, Port, Baudrate, Parity, Bytesize, Stopbits, Timeout)</span>:</span></span><br><span class="line">          <span class="keyword">try</span>:</span><br><span class="line">              self.slaveAddr = DevAddr</span><br><span class="line">              self.serial = serial.Serial(port=Port,</span><br><span class="line">                                          baudrate=Baudrate,</span><br><span class="line">                                          bytesize=Bytesize,</span><br><span class="line">                                          parity=Parity,</span><br><span class="line">                                          stopbits=Stopbits,</span><br><span class="line">                                          xonxoff=<span class="number">0</span>)</span><br><span class="line">              self.serial.timeout = Timeout</span><br><span class="line">              self.ConnType = <span class="string">'Serial'</span></span><br><span class="line">              <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">          <span class="keyword">except</span> Exception <span class="keyword">as</span> err:</span><br><span class="line">              <span class="keyword">raise</span> err</span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">Log</span><span class="params">(self, msg)</span>:</span></span><br><span class="line">          self.MBrecord.emit(msg)</span><br><span class="line"></span><br><span class="line">      <span class="comment"># 3 0 1 (23,)</span></span><br><span class="line">      <span class="comment"># 3 2 2 (34, 63)</span></span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">read</span><span class="params">(self, Func, Start, Length)</span>:</span></span><br><span class="line">          <span class="keyword">try</span>:</span><br><span class="line">              <span class="keyword">return</span> self.execute(</span><br><span class="line">                  self.slaveAddr, Func, Start, Length)</span><br><span class="line">          <span class="keyword">except</span> Exception <span class="keyword">as</span> err:</span><br><span class="line">              <span class="keyword">raise</span> err</span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">write</span><span class="params">(self, Func, Start, val)</span>:</span></span><br><span class="line">          <span class="keyword">try</span>:</span><br><span class="line">              <span class="keyword">return</span> self.execute(self.slaveAddr, Func, Start, output_value=val)</span><br><span class="line">          <span class="keyword">except</span> Exception <span class="keyword">as</span> err:</span><br><span class="line">              <span class="keyword">raise</span> err</span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">          <span class="keyword">try</span>:</span><br><span class="line">              self.ConnType</span><br><span class="line">          <span class="keyword">except</span>:</span><br><span class="line">              self.ConnType = <span class="string">''</span></span><br><span class="line">          <span class="keyword">try</span>:</span><br><span class="line">              <span class="keyword">if</span> self.ConnType == <span class="string">'Serial'</span>:</span><br><span class="line">                  self.serial.close()</span><br><span class="line">              <span class="keyword">elif</span> self.ConnType == <span class="string">'TCP'</span>:</span><br><span class="line">                  self.sock.close()</span><br><span class="line">          <span class="keyword">except</span>:</span><br><span class="line">              <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>主窗体调用 modbus</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># modbus通信class</span></span><br><span class="line">self.mb = MB()</span><br><span class="line">self.ports = self.mb.ComAutoFind()</span><br><span class="line"><span class="comment"># self.mb.Log(self.ui.txt_CMD)</span></span><br><span class="line">self.mb.MBrecord.connect(self.LogRecord)</span><br></pre></td></tr></table></figure>

</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="tosobright WeChat Pay">
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/ali.jpg" alt="tosobright Alipay">
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>Post author:</strong>
    tosobright
  </li>
  <li class="post-copyright-link">
    <strong>Post link:</strong>
    <a href="http://www.soshare.cn/2019/10/15/191015-python-scopemodbus/" title="Python+QT开发的Modbus采集软件">http://www.soshare.cn/2019/10/15/191015-python-scopemodbus/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice: </strong>
    All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> unless stating additionally.
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
            <a href="/tags/qt/" rel="tag"><i class="fa fa-tag"></i> qt</a>
          
            <a href="/tags/modbus/" rel="tag"><i class="fa fa-tag"></i> modbus</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/08/hello-world/" rel="next" title="Hello World">
                <i class="fa fa-chevron-left"></i> Hello World
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/10/16/191016-git/" rel="prev" title="Git命令学习191016">
                Git命令学习191016 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
      <script data-ad-client="ca-pub-3578624407535320" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="tosobright">
            
              <p class="site-author-name" itemprop="name">tosobright</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">51</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/tosobright" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/tosobright" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-git"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:tosobright@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:toso@soshare.cn" target="_blank" title="E-Mail2">
                      
                        <i class="fa fa-fw fa-envelope-square"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.soshare.cn/" title="Soshare" target="_blank">Soshare</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#介绍"><span class="nav-number">1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PyQT-UI-开发"><span class="nav-number">2.</span> <span class="nav-text">PyQT UI 开发</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#多线程"><span class="nav-number">3.</span> <span class="nav-text">多线程</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Modbus"><span class="nav-number">4.</span> <span class="nav-text">Modbus</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2010 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tosobright</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







  <div style>
    <script src="//s95.cnzz.com/z_stat.php?id=1726916&web_id=1726916" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: true,
        appId: 'TMSskYT1d5742mMn1W68iohd-gzGzoHsz',
        appKey: 'dIOnzLoKHUh71UF48oH6r0Qe',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("TMSskYT1d5742mMn1W68iohd-gzGzoHsz", "dIOnzLoKHUh71UF48oH6r0Qe");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  

</body>
</html>
